package io.gitee.zicai.stream.send

import io.gitee.zicai.stream.processor.MsgDelayProcessor
import io.gitee.zicai.stream.processor.MsgProcessor
import io.gitee.zicai.stream.util.LogKit
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.cloud.stream.annotation.EnableBinding
import org.springframework.messaging.support.MessageBuilder
import org.springframework.stereotype.Component
import java.util.concurrent.TimeUnit

/**
 * MsgSender
 * @author zicai
 * @since 2020-05-11
 */
@Component
@EnableBinding(MsgProcessor::class)
open class MsgSender {

    @Autowired
    private lateinit var msgProcessor: MsgProcessor
    @Autowired
    private lateinit var msgDelayProcessor: MsgDelayProcessor

    open fun send(msg: Int) {
        val type = if (msg % 2 == 0) "even" else "odd"
        val msgBuilder = MessageBuilder.withPayload(msg).setHeader("type", type)

        if (msg == 5) {
            msgBuilder.setHeader("x-delay", TimeUnit.SECONDS.toMillis(msg.toLong()))
        }

        msgProcessor.output().send(msgBuilder.build())
        println("${LogKit.nowTime()} - send to mq -> $msg")
    }

    open fun sendDelayMsg(msg: Int) {
        // 发送消息后，需要延迟指定时间才能接收到
        // 注意：延迟最大支持的时间为 4294967295 毫秒，约49天
        val msgBuilder = MessageBuilder.withPayload(msg)
        msg.toLong()
                .let { TimeUnit.SECONDS.toMillis(it) }
                .also { msgBuilder.setHeader("x-delay", it) }
        (msg.takeIf { it == 5 }?.let { "error" } ?: "ok")
                .also { msgBuilder.setHeader("type", it) }
        msgDelayProcessor.output().send(msgBuilder.build())
        println("${LogKit.nowTime()} - send to delay mq -> $msg")
    }
}